package com.zjt.smart.ui.base;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;

import com.zjt.smart.R;
import com.zjt.smart.ui.base.swipeback.SwipeBackLayout;

import butterknife.Bind;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2017</p>
 * <P>Company: </p>
 *
 * @author zhengjianting
 * @time 2017/8/28 0028 上午 10:22
 */

public abstract class ToolbarActivity extends BaseActivity {

    @Bind(R.id.toolbar)
    protected Toolbar mToolbar;

    protected SwipeBackLayout mSwipeBackLayout;

    /*
     * Whether this Activity can back by click left-top back-button.
     */
    protected boolean canBack() {
        return true;
    }

    // A hook method that do something when click the Toolbar.
    protected void onToolbarClick() {
        Fragment fragment = getVisibleFragment();
        if (fragment != null && fragment instanceof ScrollFragment) {
            ((ScrollFragment) fragment).smoothScrollTo(0);
        }
    }

    @SuppressWarnings("ConstantConditions")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) throws RuntimeException {
        super.onCreate(savedInstanceState);
        //Toolbar
        if (mToolbar == null) {
            throw new RuntimeException("Toolbar must be set at id(toolbar)");
        }
        setToolbarParameter(mToolbar);
        setSupportActionBar(mToolbar);
        mToolbar.setOnClickListener(view -> onToolbarClick());

        //SwipeBack
        setSwipeBackEnable(canBack());
        if (canBack()) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            // Set SwipeBack Action.
            mSwipeBackLayout = getSwipeBackLayout();
            mSwipeBackLayout.setEdgeTrackingEnabled(SwipeBackLayout.EDGE_LEFT);
            mToolbar.setNavigationOnClickListener(v -> finish());
        }
    }

    protected void setToolbarParameter(Toolbar toolbar) {
        toolbar.setTitleTextAppearance(getParent(), R.style.ToolbarTextStyle);
    }

    public Toolbar getToolbar() {
        return mToolbar;
    }

    //Set the home button listener which can finish this activity
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}
